 
package com.farsunset.ichat.cim.push;

import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.appleframework.config.core.PropertyConfigurer;
import com.dbay.apns4j.IApnsService;
import com.dbay.apns4j.model.Payload;
import com.farsunset.cim.nio.mutual.Message;
import com.farsunset.cim.nio.session.CIMSession;
import com.farsunset.cim.nio.session.SessionManager;
import com.farsunset.ichat.cim.session.MessageManager;
import com.farsunset.ichat.common.util.StringUtil;

/**
 * 消息发送实现类
 * 
 */
public class DefaultMessagePusher implements  CIMMessagePusher {


	private final Log log = LogFactory.getLog(getClass());
	
	private SessionManager sessionManager;
	
	private MessageManager messageManager;
	
	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

	public void setMessageManager(MessageManager messageManager) {
		this.messageManager = messageManager;
	}

	/**
	 * 推送到ios
	 * @param msg
	 * @param clusterSession
	 * @param localSession
	 */
	public void pushToIos(Message msg,CIMSession localSession){			
		String deviceToken = msg.getDeviceToken();
		// ios 立即发送  在线则通过socket发送，不在线则通过apns发送
		if(msg.isOffHand() == true && localSession != null && localSession.isConnected()){
			localSession.write(msg);
			return;
		}		
		try {
			deliverByANPS(msg,deviceToken);
		} catch (Exception e) {
			log.error("消息推送失败:" + e.getMessage() + ":" + msg.toString());
		}
	}
	
	/**
	 * 推送到android
	 * @param msg
	 * @param clusterSession
	 * @param localSession
	 */
	public void pushToAndroid( Message msg, CIMSession localSession){
		// android 首先通过socket发送
		if(localSession != null && localSession.isConnected()){
			System.out.println("wwwwwwwwwwwwwwwwwwwww:"  + msg);
			localSession.write(msg);			
			return;
		}
		
		// 如果不在线 根据是否立即发送 和 是否离线进行离线消息存储 ，等待用户登录时推送离线消息  
		if(msg.isOffHand() == false && msg.isOffline() == true ){
			messageManager.setOfflineMessage(msg.getReceiver(), msg);
			return;
		}
		
		// 或者无集群session时就发离线
		CIMSession session = sessionManager.getSession(msg.getReceiver());	
		if(session == null){
			messageManager.setOfflineMessage(msg.getReceiver(), msg);
			return;
		}
	}

	/**
     * 向用户发送消息
     * @param msg
     */
	public void pushMessageToUser(Message msg) {		
		if(StringUtil.isEmpty(msg.getMid())){
			msg.setMid(UUID.randomUUID().toString());
		}		
		if(StringUtil.isEmpty(msg.getReceiver())){
			return;
		}	
		
		CIMSession session = sessionManager.getSession(msg.getReceiver());
		// ios 消息通过 apns 推送 deviceToken 不为空则为ios
		if (StringUtil.isNotEmpty(msg.getDeviceToken())) {
			pushToIos(msg, session);
			return;
		}
		// android 消息推送 deviceToken为空则为android
		if (StringUtil.isEmpty(msg.getDeviceToken())) {
			pushToAndroid(msg, session);
			return;
		}
	}	

	/**
	 * apns 推送消息
	 * @param msg
	 * @param deviceToken
	 * @throws Exception
	 */
	public void deliverByANPS(Message msg,String deviceToken) throws Exception {		
		IApnsService service = Apns4jServiceFactoryBean.getApnsService(Boolean.valueOf(PropertyConfigurer.getString("apns.isdev")));		
		Payload payload = new Payload();
		payload.setAlert(msg.getContent());
		payload.setBadge(1);
		payload.setSound("defult");
		payload.addParam("mid", msg.getMid());		
		payload.addParam("type", msg.getType());
		payload.addParam("data", msg.getMapStr());
		service.sendNotification(deviceToken, payload);
	}

}
